package news.service;

import com.auth0.jwt.interfaces.DecodedJWT;
import news.dao.UserCollectionDao;
import news.dao.UserDao;
import news.model.*;
import news.util.EMAIL;
import news.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class FrontUserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserCollectionDao userCollectionDao;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JavaMailSender mailSender;

    public void saveComment(Integer newsid, String comment, String userToken) {
        //1.从用户token中解析用户id
        DecodedJWT decodedJWT = JWTUtil.getTokenInfo(userToken);
        System.out.println(decodedJWT.getClaim("id"));
        int userId = JWTUtil.getTokenInfo(userToken).getClaim("id").asInt();
        //2.敏感词检测
        //3.将评论内容插入数据库
        userDao.saveComment(newsid,userId,comment);
    }


    public int createYzm(String email){
        //验证此邮箱有没有注册过 1-注册过 2-成功
        if(email.equals("380558095@qq.com")){
            return EMAIL.EMAIL_IS_REG;
        }
        String random = random();
        //redis存储验证码
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(email,random,5, TimeUnit.MINUTES);

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("1178488909@qq.com");
        message.setTo(email);
        message.setSubject("主题：简单邮件");
        message.setText("测试邮件内容:"+random);
        mailSender.send(message);
        return EMAIL.EMAIL_REG_SUCCESS;
    }

    public String random(){
        Random random = new Random();
        int randomNum = random.nextInt(1000000);
        String randomCode = String.format("%06d", randomNum);
        return randomCode;
    }

    public int save(User user) {
        //通过邮箱从redis获取验证码，与提交的进行对比
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Boolean aBoolean = redisTemplate.hasKey(user.getEmail());
        if(!aBoolean){
            return 1;//验证码过期
        }
        String o = (String) valueOperations.get(user.getEmail());
        if(o.equals(user.getYzm())){
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
            userDao.save(user);
            return 3;//保存成功
        }
        return 2;//验证码错误
    }

    public CommonResult userLogin(User user) {
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        User user1 = userDao.userLogin(user);
        if(user1==null){
            return new CommonResult(201,"账号或者密码错误");
        }else{
            if(user1.getStatus()==0){
                return new CommonResult(202,"账号已被禁用");
            }else{
                //token生成
                user1.setToken(JWTUtil.getUserToken(user1));
                return new CommonResult(200,user1,"登录成功");
            }
        }
    }

    public Boolean checkUserIsDZ(String newsid, String userToken) {
        int userId = JWTUtil.getTokenInfo(userToken).getClaim("id").asInt();
        //去redis中查询是否点过赞
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Integer dz = (Integer) valueOperations.get("新闻:" + newsid + "用户:" + userId + "dz");
        if(dz==null){
            return false;
        }else{
            return true;
        }
    }

    public Boolean checkUserIsSC(String newsid, String userToken) {
        int userId = JWTUtil.getTokenInfo(userToken).getClaim("id").asInt();
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Integer sc = (Integer) valueOperations.get("新闻:" + newsid + "用户:" + userId + "sc");
        List<User> user = userDao.checkUserIsSC(newsid,userId);
        if(sc==null) {
            return false;
        }
        return true;
    }

    public void dz(String newsid, String userToken, Boolean isDZ) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        int userId = JWTUtil.getTokenInfo(userToken).getClaim("id").asInt();
        if(isDZ){//取消点赞
            //点赞数减一
            valueOperations.decrement("新闻id:"+newsid + "dzCount");
            //删除点赞记录
            redisTemplate.delete("新闻:" + newsid + "用户:" + userId + "dz");
        }else{
            //点赞数加一
            valueOperations.increment("新闻id:"+newsid + "dzCount");
            //记录点赞数
            valueOperations.set("新闻:" + newsid + "用户:" + userId + "dz",1);
        }
    }

    public void sc(Integer newsid, String userToken, Boolean isSC,String title) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        int userId = JWTUtil.getTokenInfo(userToken).getClaim("id").asInt();
        if(isSC){
            //取消收藏
            userCollectionDao.delete(newsid,userId);
            valueOperations.decrement("新闻id:"+newsid + "scCount");
        }else{
            //收藏
            userCollectionDao.insert(newsid,userId,title);
            valueOperations.increment("新闻id:"+newsid + "scCount");
        }
    }

    public void saveInfo(String nickname,String password,
                         String phone,String gender,String userToken) {
        String newPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        int userId = JWTUtil.getTokenInfo(userToken).getClaim("id").asInt();
        userDao.saveInfo(nickname,newPassword,phone,gender,userId);
    }

    public User getUserInfo(String userToken) {
        int userId = JWTUtil.getTokenInfo(userToken).getClaim("id").asInt();
        return userDao.getUserInfo(userId);
    }


    public List<News> collectionNews(String userToken) {
        int userId = JWTUtil.getTokenInfo(userToken).getClaim("id").asInt();
        return userCollectionDao.collectionNews(userId);
    }

    public List<List<News>> commentNews(String userToken) {
        int userId = JWTUtil.getTokenInfo(userToken).getClaim("id").asInt();
        return userCollectionDao.commentNews(userId);
    }
}
